package com.autonavi.yunda.yunji.configuration;

import com.autonavi.yunda.yunji.common.utils.JsonUtils;
import com.autonavi.yunda.yunji.common.web.entity.GlobalResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author cizhong.wcs
 * @date 2022/1/29 2:32 下午
 *
 * 接口响应信息的全局配置接口
 */
@Slf4j
@RestControllerAdvice
public class AmapResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    /**
     * 此处如果返回false , 则不执行当前Advice的业务
     */
    @Override
    public boolean supports(@NotNull MethodParameter returnType, @NotNull Class converterType) {
        return true;
    }


    @Override
    public Object beforeBodyWrite(Object body,
                                  @NotNull MethodParameter returnType,
                                  @NotNull MediaType selectedContentType,
                                  @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @NotNull ServerHttpRequest request,
                                  @NotNull ServerHttpResponse response) {
        if (request.getURI().getPath().contains("/xxl-job-admin")) {
            return body;
        }
        if (body == null) {
            if (returnType.getMethod().getReturnType().isAssignableFrom(String.class)) {
                return JsonUtils.toString(GlobalResponse.successResult(body));
            }
            return GlobalResponse.successResult(body);
        }
        if (body instanceof GlobalResponse) {
            return body;
        }
        //处理string类型的返回值
        //当返回类型是String时，用的是StringHttpMessageConverter转换器，无法转换为Json格式
        if (body instanceof String) {
            return JsonUtils.toString(GlobalResponse.successResult(body));
        }
        return GlobalResponse.successResult(body);
    }

}
